﻿
var lazyLoad = {
	/// <summary>
	/// img标签中的存放图片路径的自定义属性名称
	/// </summary>
	AttributeName: "lazyload",
	/// <summary>
	/// 初始化。自动加载第一张图片。
	/// </summary>
	Init: function(v) {
		if (v != undefined && v != null && typeof (v) == "string") {
			this.AttributeName = v;
		}

		if ($("img[" + this.AttributeName + "]").size() > 0) {
			var src = $("img[" + this.AttributeName + "]").eq(0).attr(this.AttributeName);
			$("img[" + this.AttributeName + "]").eq(0).attr("src", src);
			$("img[" + this.AttributeName + "]").eq(0).removeAttr(this.AttributeName);
		}
		$("img[" + this.AttributeName + "]").hide();
	},
	/// <summary>
	/// 当scroll事件被触发时，进行加载图片的操作
	/// </summary>
	LoadImage: function(scrolltop) {

		//获取目前第一张需延迟加载的图片，无图片的话就终止
		var currentObj = null;
		if ($("img[" + this.AttributeName + "]").size() > 0) {
			currentObj = $("img[" + this.AttributeName + "]").eq(0);
			currentObj.show();
		}
		else {
			return false;
		}

		//获取窗体的高度
		var windowHeight = $(window).height();

		//获取当前图片相对于页面顶部的偏移量
		var _scrollTop = currentObj.offset().top - windowHeight;
		if ($.browser.safari) {
			_scrollTop = _scrollTop - scrolltop;
		}
		//根据scrollTop判断是否显示图片
		if (parseInt(scrolltop) >= parseInt(_scrollTop)) {
			var src = currentObj.attr(this.AttributeName);
			currentObj.attr("src", src);
			currentObj.removeAttr(this.AttributeName);
		}

	},
	/// <summary>
	/// 启动延时加载
	/// <params key="v">img标签中的存放图片路径的自定义属性名称</params>
	/// </summary>
	Run: function(v) {

		this.Init(v);

		var _this = this;
		if ($("img[" + this.AttributeName + "]").size() > 0) {
			$(window).bind("scroll", function() {
				_this.LoadImage($(this).scrollTop());
			});
		}
	}
};
lazyLoad.Run();
